<template>
	<view id="form">
		<u--form :model="form" :rules="rules" ref="form1">
			<u-form-item labelWidth="70" label="巡检类型" borderBottom @click="showType = true">
				<text v-for="item in typeOpts[0]" v-if="item.id === form.type">{{item.title}}</text>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item labelWidth="70" label="项目名称" required borderBottom prop="projectName" @click="proShow = true">
				<u--input v-model="form.projectName" disabled disabledColor="#fff" placeholder="项目名称" border="none">
				</u--input>
				<u-button class="btn-add" plain icon="plus" type="primary" size="mini" slot="right"
					@click="toAddProject"></u-button>
			</u-form-item>
			<u-form-item labelWidth="70" label="所属区域" required prop="areaName">
				<u--input v-model="form.areaName" disabled disabledColor="#fff" placeholder="选择所属区域" border="none">
				</u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item labelWidth="70" label="定位" required borderBottom prop="locationAddr" @click="onShowMapWrap">
				<u--input v-model="form.locationAddr" disabled disabledColor="#fff" placeholder="选择定位" border="none">
				</u--input>
				<u-icon slot="right" name="map-fill"></u-icon>
			</u-form-item>
			<view class="selected-content" v-for="item in jcOpts" :key="item.id">
				<block v-for="(val, index) in selectedValues" :key="index" v-if="val == item.id">
					<view class="content-abs" @click="deleteSelected(item.id)">
						<u-icon name="trash-fill" color="#999" size="16"></u-icon>
					</view>
					<u-form-item labelWidth="70" label="检查项" required>
						<u--input :value="item.title" disabled disabledColor="#fff" border="none">
						</u--input>
					</u-form-item>
					<u-form-item labelWidth="70" required :prop="`list${item.id}`" label="图片">
						<u-upload
							multiple
							:name="item.id"
							:capture="['camera']"
							:fileList="form['list' + item.id]"
							:width="40"
							:height="40"
							:maxCount="5"
							@delete="deletePic(item.id)"
							@afterRead="fileUpload"
						>
						</u-upload>
					</u-form-item>
					<u-form-item labelWidth="70" borderBottom required label="检查内容" :prop="`content${item.id}`">
						<u--input v-model="form['content' + item.id]" placeholder="输入整改要求"></u--input>
					</u-form-item>
				</block>
			</view>
			<u-form-item borderBottom>
				<view class="addbtn1">
					<u-button v-if="typeValues.length <= 6" size="small" type="primary" plain icon="plus" @click="addXj">添加检查项</u-button>
				</view>
			</u-form-item>
			<u-form-item labelWidth="100" label="是否需要整改" borderBottom required prop="isRectify1" @click="showRectify = true">
				<u--input v-model="form.isRectify1" disabled disabledColor="#fff" placeholder="请选择是否需要整改" border="none">
				</u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<view v-if="form.isRectify === 1">
				<u-form-item labelWidth="70" label="整改期限" required borderBottom prop="rectifyTime"
					@click="showCalendar = true">
					<u--input v-model="form.rectifyTime" disabled disabledColor="#fff" placeholder="请选择整改期限"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item labelWidth="70" required borderBottom prop="rectifyDemand" label="整改要求">
					<u-textarea v-model="form.rectifyDemand" placeholder="输入整改要求"></u-textarea>
				</u-form-item>
				<u-form-item labelWidth="100" borderBottom prop="rectifyPersonName" label="整改责任人">
					<u--input v-model="form.rectifyPersonName" placeholder="(项目负责人)"></u--input>
				</u-form-item>
			</view>
		</u--form>
		<view class="submit-btn">
			<u-button type="primary" shape="circle" color="linear-gradient(to right, #2595f9, #1eb8ee)"
				:disabled="submitDisabled" :loading="submitLoading" :text="submitText" @click="onSubmit"></u-button>
			<!-- <text class="btn-add" :loading="submitLoading" @click="onSubmit">{{ submitText }}</text> -->
		</view>
		<u-picker closeOnClickOverlay :show="showRectify" :columns="rectifyOpts" @cancel="onRecCancel"
			@confirm="onRecConfirm" @close="onCloseRec" keyName="title"></u-picker>
		<u-picker closeOnClickOverlay :show="showType" :columns="typeOpts" @cancel="onTypeCancel" @close="onCloseType"
			@confirm="onTypeConfirm" keyName="title"></u-picker>
		<u-datetime-picker :show="showCalendar" v-model="value1" mode="date" @confirm="confirmCalendar"
			@close="calendarClose" @cancel="cancelCalendar"></u-datetime-picker>
		<u-popup :show="showMap" @close="onCloseMap" @open="onShowMap">
			<view class="map_container">
				<map class="map" id="map" :longitude="position.longitude" :latitude="position.latitude"
					:markers="markers" scale="16"></map>
			</view>
			<view class="map_text">
				<view>
					<text class="h1">{{position.name}}</text>
					<text>{{position.desc}}</text>
				</view>
				<view>
					<u-button size="small" type="primary" text="提交" @click="onLocation"></u-button>
				</view>
			</view>
		</u-popup>
		<u-popup :show="xjShow" mode="bottom" @close="onCloseXj">
			<view class="jc-content">
				<u-checkbox-group borderBottom v-model="typeValues" placement="column" iconPlacement="right" :labelDisabled="true">
					<u-checkbox :customStyle="{ marginBottom: '8px' }" v-for="(item, index) in jcOpts" :key="index"
						:label="item.title" :name="item.id">
					</u-checkbox>
				</u-checkbox-group>
				<!-- 				<u-radio-group borderBottom v-model="" placement="column" iconPlacement="right" @change="onChange">
					<u-radio v-for="item in jcOpts" :customStyle="{ marginBottom: '16px' }" :key="item.id" :name="item.id" :label="item.title"></u-radio>
				</u-radio-group> -->
				<view class="addbtn">
					<u-button size="small" type="primary" @click="addJc">添加</u-button>
				</view>
			</view>
		</u-popup>
		<u-popup closeOnClickOverlay :show="proShow" mode="bottom" @close="searchClose">
			<view class="view-content">
				<view class="search" id="search_box">
					<view class="search_main">
						<u-search placeholder="搜索项目名" v-model="keyword" :show-action="false" @change="onSearch"></u-search>
					</view>
				</view>
				<scroll-view :scroll-y="true" class="project-list">
					<view class="project-item" v-for="item in projectList" :key="item.projectId" @click="onSelect(item)">{{item.projectName}}</view>
				</scroll-view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	const amapFile = require('@/utils/amap-wx.130')
	const configMap = require('@/utils/config.js')
	import config from '@/utils/defaultConfig'
	import {
		getAreaList,
		getProjectList
	} from '@/api/global'
	import {
		createNo,
		addPatrol
	} from '@/api/form'
	import apis from '@/api/apis'
	import {
		ACCESS_TOKEN
	} from '@/store/mutaction-types'

	export default {
		data() {
			return {
				keyword: '',
				proShow: false,
				xjShow: false,
				myCanvas: null,
				myCtx: null,
				submitText: '提交',
				submitLoading: false,
				submitDisabled: false,
				showArea: false,
				cityLoading: false,
				showType: false,
				actions: [],
				cityColumns: [],
				areaList: [],
				maxSize: 500,
				value1: Number(new Date()),
				typeValues: [],
				selectedValues: [],
				form: {
					projectName: '',
					areaName: '',
					type: 0,
					locationAddr: '',
					isRectify: '',
					isRectify1: ''
				},
				rules: {
					projectName: [{
						required: true,
						message: '必须填写项目名称',
						trigger: ['blur']
					}],
					locationAddr: [{
						required: true,
						message: '必须选择定位',
						trigger: ['blur']
					}],
					areaName: [{
						required: true,
						message: '必须选择所属区域',
						trigger: ['blur']
					}],
					isRectify1: [{
						required: true,
						message: '必须选择是否整改',
						trigger: ['blur']
					}],
					rectifyTime: [{
						required: true,
						message: '必须选择整改期限',
						trigger: ['blur']
					}],
					rectifyDemand: [{
						required: true,
						message: '必须填写整改内容',
						trigger: ['blur']
					}]
				},
				rectifyOpts: [
					config.isRectify
				],
				typeOpts: [
					config.type
				],
				jcOpts: config.xjType,
				showCalendar: false,
				showRectify: false,
				projectList: [],
				showMap: false,
				position: {},
				markers: [],
				videoList: [],
				proList: [],
				textType: '',
				content: {}
			}
		},
		created() {
			this.getBusinessNo()
		},
		methods: {
			getBusinessNo() {
				createNo().then(res => {
					const no = res.data.msg
					const arr = no.split(',')
					this.form.checkNo = arr[0]
					this.form.businessId = arr[1]
				})
				const key = configMap.Config.key
				const myAmapFun = new amapFile.AMapWX({
					key: key
				})
				uni.authorize({
					scope: 'scope.userLocation',
					success: () => {
						uni.getLocation({
							type: 'gcj02',
							success: res => {
								myAmapFun.getRegeo({
									location: `${res.longitude},${res.latitude}`,
									success: add => {
										this.form.locationAddr = add[0].name
										this.form.latitude = res.latitude
										this.form.longitude = res.longitude
									},
									fail: error => {
										console.log(error)
									}
								})
							}
						})
					}
				})
			},
			deletePic(event) {
				this.form[`list${event.name}`].splice(event.index, 1)
			},
			calendarClose() {
				this.showCalendar = false
			},
			cancelCalendar() {
				this.showCalendar = false
			},
			onRecCancel() {
				this.showRectify = false
			},
			onSelect(opt) {
				this.form.projectId = opt.projectId
				this.form.projectName = opt.projectName
				this.form.areaName = opt.areaFullPath
				this.form.areaId = opt.areaId
				this.searchClose()
			},
			searchClose () {
				this.keyword = ''
				this.projectList = []
				this.proShow = false
			},
			onCloseRec() {
				this.showRectify = false
			},
			addXj() {
				this.xjShow = true
			},
			onCloseMap() {
				this.showMap = false
			},
			confirmCalendar(e) {
				this.showCalendar = false
				this.form.rectifyTime = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')
			},
			onShowMap() {},
			onShowMapWrap() {
				uni.authorize({
					scope: 'scope.userLocation',
					success: () => {
						uni.chooseLocation({
							success: res => {
								this.form.longitude = res.longitude
								this.form.latitude = res.latitude
								this.form.locationAddr = res.address
							},
							fail: err => {
								console.log(err)
							}
						})
					}
				})
			},
			onSubmit() {
				const app = this
				const items = {}
				app.$refs.form1.validate().then(res => {
					app.submitLoading = true
					app.submitText = '上报中'
					for (const k in app.selectedValues) {
						const obj = {}
						// obj['id'] = app.selectedValues[k]
						for (const j in app.jcOpts) {
							if (app.selectedValues[k] === app.jcOpts[j].id) {
								const arr = []
								obj['content'] = this.form[`content${app.selectedValues[k]}`]
								for (const l in this.form[`list${app.selectedValues[k]}`]) {
									arr.push(this.form[`list${app.selectedValues[k]}`][l].url)
								}
								obj['image'] = arr.join(',')
							}
						}
						items[app.selectedValues[k]] = obj
					}
					const form = app.form
					form.items = items
					addPatrol(form).then(res => {
						if (res.data.code === 200) {
							app.submitLoading = false
							app.submitText = '上报'
							uni.$u.toast('提交成功')
							uni.switchTab({
								url: '/pages/index/index'
							})
						} else {
							uni.$u.toast(res.msg)
							app.submitLoading = false
							app.submitText = '上报'
							return false
						}
					}).catch(err => {
						uni.$u.toast(err)
						app.submitLoading = false
						app.submitText = '上报'
						return false
					})
				}).catch(errors => {
					app.submitLoading = false
					app.submitText = '上报'
					return false
				})
			},
			onCloseType() {
				this.showType = false
			},
			onCloseXj () {
				this.xjShow = false
			},
			onTypeCancel() {
				this.showType = false
			},
			onTypeConfirm(e) {
				this.form.type = e.value[0].id
				this.form.typeName = e.value[0].title
				this.showType = false
			},
			onRecConfirm(e) {
				this.form.isRectify = e.value[0].id
				this.form.isRectify1 = e.value[0].title
				this.showRectify = false
			},
			onCityConfirm(e) {
				// 街道办事处等没有二级选择，所以报错
				if (e.value[0].children.length == 0) {
					this.form.areaName = e.value[0].areaName
					this.form.areaId = e.value[0].id
				} else {
					this.form.areaName = e.value[1].areaName
					this.form.areaId = e.value[1].id
				}
				this.showArea = false
			},
			async fileUpload(event) {
				console.log(event)
				const app = this
				this.submitText = '上传中'
				this.submitDisabled = true
				let lists = [].concat(event.file)
				let fileListLen = this.form[`list${event.name}`].length
				lists.map((item) => {
					this.form[`list${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					// const url = await this.addMask1(lists[i].url)
					let result = await this.uploadFilePromise(lists[i].url)
					let item = this.form[`list${event.name}`][fileListLen]
					this.form[`list${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: 'https://bc-p2-file.oss-cn-zhangjiakou.aliyuncs.com/' + result.msg
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url, type) {
				const app = this
				const data = {}
				const API_BASE_URL1 = 'http://192.168.124.20:8888'
				const API_BASE_URL2 = 'https://p2.xuzhouzhihui.com/api'
				data['businessId'] = this.form.businessId
				data['businessType'] = 'APP_PATROL_ALL_IMAGE'
				return new Promise((resolve, reject) => {
					const a = uni.uploadFile({
						url: API_BASE_URL2 + apis.Upload2,
						filePath: url,
						name: 'file',
						header: {
							'Authorization': 'Bearer ' + uni.getStorageSync(ACCESS_TOKEN)
						},
						formData: data,
						success: res => {
							setTimeout(() => {
								resolve(JSON.parse(res.data))
								this.submitText = '上报'
								this.submitDisabled = false
							}, 500)
						},
						fail: error => {
							uni.$u.toast(error)
						}
					})
				})
			},
			toAddProject(e) {
				uni.navigateTo({
					url: '../project/project'
				})
			},
			addJc () {
				const app = this
				app.selectedValues = uni.$u.deepClone(app.typeValues)
				for (const k in app.selectedValues) {
					app.rules['content' + app.selectedValues[k]] = [{
						required: true,
						message: '必须填写检查内容',
						trigger: ['blur']
					}]
					app.rules['list' + app.selectedValues[k]] = [{
						type: 'array',
						required: true,
						min: 1,
						message: '至少上传1张图片',
						trigger: ['change']
					}]
					app.form['list' + app.selectedValues[k]] = []
				}
				app.xjShow = false
			},
			deleteSelected (id) {
				const app = this
				uni.showModal({
					title: "提示",
					content: "是否删除当前检查项",
					showCancel: false,
					success: config => {
						if (config.confirm) {
							app.selectedValues.splice(app.selectedValues.indexOf(id), 1)
							app.typeValues.splice(app.selectedValues.indexOf(id), 1)
							app.form['list' + id] = []
						}
					}
				})
			},
			onSearch () {
				this.projectList = []
				const params = {}
				params['projectName'] = uni.$u.trim(this.keyword, 'all')
				getProjectList(params).then(res => {
					this.projectList = res.data.data
				}).catch(error => {
					console.log(error)
				})
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.form1.setRules(this.rules)
		}
	}
</script>

<style lang="scss" scoped>
	#form {
		padding: 0 20upx 300upx;
	}
	.view-content {
		padding: 20upx;
		.search {
			width: 100%;
			height: 100rpx;
			background-color: #fff;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		
		.search_main {
			width: 100%;
		}
		.project-list {
			width: 100%;
			height: 600upx;
			.project-item {
				padding: 15upx 0;
				border-bottom: 1px solid #eee;
			}
		}
	}
	.addbtn {
		width: 200upx;
		margin: 0 auto;
	}
	
	.addbtn1 {
		width: 260upx;
		margin: 0 auto;
	}

	.btn-add {
		width: 40px;
	}

	.map_container {
		width: 750upx;
		height: 750upx;

		#map {
			width: 750upx;
			height: 750upx;
		}
	}

	.map_text {
		background: #fff;
		padding: 0 15px;
		display: flex;
		justify-content: space-between;
		align-items: center;

		text {
			margin: 5px 0;
			display: block;
			font-size: 12px;
		}

		.h1 {
			margin: 15px 0;
			font-size: 15px;
		}
	}

	.jc-content {
		padding: 40upx;
	}
	
	.selected-content {
		position: relative;
		.content-abs {
			position: absolute;
			right: 5upx;
			top: 5upx;
			z-index: 9999;
		}
	}
	
	.submit-btn {
		position: fixed;
		bottom: 0;
		left: 50%;
		margin-left: -150upx;
		width: 300upx;
		z-index: 9999;
		background-color: #ffffff;
		height: 100upx;

		.btn-add {
			display: block;
			width: 40%;
			height: 72upx;
			line-height: 72upx;
			background-color: #55aaff;
			margin: 18upx auto;
			border-radius: 40upx;
			text-align: center;
			font-size: 32upx;
			color: #fff;
			background-image: linear-gradient(to right, #2595f9, #1eb8ee);
			box-shadow: 0 1px 4px 0px rgba(30, 184, 238, 0.3);
		}
	}
</style>
